package com.chenfei.captcha.service.impl;


import com.chenfei.captcha.common.MarketRespEnum;
import com.chenfei.captcha.filter.FilterFactory;
import com.chenfei.captcha.filter.predefined.DoubleRippleFilterFactory;
import com.chenfei.captcha.req.CaptchaReq;
import com.chenfei.captcha.resp.CaptchaResEntity;
import com.chenfei.captcha.resp.ResponseEntity;
import com.chenfei.captcha.service.Captcha;
import com.chenfei.captcha.service.CaptchaService;
import com.chenfei.captcha.utils.color.RandomColorFactory;
import com.chenfei.captcha.utils.text.TextRenderer;
import com.dianping.cat.message.spi.codec.BufferWriter;
import io.netty.buffer.ByteBuf;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.util.Random;
import java.util.UUID;

/**
 * @author chenfei
 * @description 验证码生成类
 * @since 2018/4/4
 */
@Service
@Slf4j
public class CaptchaServiceImpl implements CaptchaService {
	/** 图片宽度 */
	private int width = 150;
	/** 图片高度 */
	private int height = 60;
	/** 字符长度 */
	private int charLength = 4;
	private static String captchaStr;
	private TextRenderer textRenderer;
	private RandomColorFactory colorFactory;
	private FilterFactory filterFactory;

	public CaptchaServiceImpl(){
		colorFactory = new RandomColorFactory();
		filterFactory = new DoubleRippleFilterFactory();
		textRenderer = new TextRenderer();
	}

	@Override
	public ResponseEntity<CaptchaResEntity> getCaptcha() {
		ResponseEntity baseResEntity = new ResponseEntity(MarketRespEnum.SUCCESS);
		try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
			Captcha captcha = createCaptcha();
			ImageIO.write(captcha.getImage(), "png", baos);
			log.info("图形验证码生成成功【"+captcha.getWord()+"】");
            byte[] bytes = baos.toByteArray();

			FileOutputStream fileOutputStream = new FileOutputStream("d:/code.png");
			fileOutputStream.write(bytes);
			fileOutputStream.flush();
			fileOutputStream.close();

			String captCode = getUUIDStr();
			CaptchaResEntity captchaResEntity = new CaptchaResEntity();
			captchaStr = captcha.getWord();
			//JedisPoolClient.getInstance().set(captCode,captcha.getWord(),CAPTCHA_OVERDUE_TIMES);
			captchaResEntity.setCaptcha(bytes);
			captchaResEntity.setCaptCode(captCode);
			baseResEntity.setData(captchaResEntity);
		} catch (Exception e){
			e.printStackTrace();
			log.info("获取验证码失败");
		}
		return baseResEntity;
	}

	@Override
	public boolean verifyCaptcha(CaptchaReq captchaReq) {
		if(!StringUtils.isEmpty(captchaReq.getCaptcha()) && captchaReq.getCaptcha().equals(captchaStr)){
			return true;
		}
		return false;
	}

	private Captcha createCaptcha() {
		BufferedImage bufImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
		fillBackground(bufImage);
		String word = getNextWord(charLength);
		textRenderer.draw(word, bufImage, colorFactory);
		bufImage = filterFactory.applyFilters(bufImage);
		return new Captcha(bufImage,word);
	}

	/**
	 * 填充背景颜色
	 * @param dest
	 */
	private void fillBackground(BufferedImage dest) {
		Graphics g = dest.getGraphics();
		g.setColor(new Color(238, 243, 249));
		g.fillRect(0, 0, dest.getWidth(), dest.getHeight());
	}

	/**
	 * 获取随机字符串
	 * @return
	 */
	private String getNextWord(int charLength) {
		String characters = "0123456789";
		Random rnd = new Random();
		StringBuffer sb = new StringBuffer();
		StringBuffer chars = new StringBuffer(characters);

		while(sb.length()<charLength){
			int j = rnd.nextInt(chars.length());
			char c = chars.charAt(j);
			if(sb.indexOf(String.valueOf(c))==-1){
			 	sb.append(c);
			}
		}
		return sb.toString();
	}

	private String getUUIDStr(){
		return UUID.randomUUID().toString().replace("-","");
	}
}
